package com.mytech.cslive.communication_handlers;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
import java.net.MulticastSocket;
import java.net.SocketException;
import java.util.ArrayList;

import com.mytech.cslive.infrastructure.LogFile;

public class UDPConnectionHandler extends ConnectionHandler {
	public static final String TAG = "CSLive.UDPConnectionHandler";
	
	ArrayList<InetSocketAddress> addressList;
	private MulticastSocket clientSocket;
	
	public UDPConnectionHandler(InetSocketAddress... socketAddresses)
			throws SocketException {
		try {
			clientSocket = new MulticastSocket();
			
			clientSocket.setTimeToLive(255);
		} catch (IOException ex) {
			// TODO
		}
		
		addressList = new ArrayList<InetSocketAddress>();
		
		for (InetSocketAddress address : socketAddresses) {
			boolean result = addressList.add(address);
			
			if (!result) {
				LogFile.log(address.toString() + " failed to add to adress list!");
			}
		}
	}
	
	public MulticastSocket getClientSocket() {
		return clientSocket;
	}
	
	@Override
	void connect(InetSocketAddress... socketAddress) throws SocketException {
		// Do nothing
	}

	@Override
	void disconnect() {
		this.getClientSocket().disconnect();
	}

	@Override
	void sendData(byte[] data) throws IOException {
		for (InetSocketAddress address : addressList) {
			DatagramPacket sendPacket = new DatagramPacket(
					data, data.length, address.getAddress(), address.getPort());
			
			this.getClientSocket().send(sendPacket);
		}

	}

	@Override
	public void releaseAddresses() {
		this.disconnect();
	}
}
